package com.homegoods.orderinfodetail.ui.activity;

import android.animation.ArgbEvaluator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.homegoods.aroutercomment.ARouterPath;
import com.homegoods.aroutercomment.UserService;
import com.homegoods.orderinfodetail.R;
import com.homegoods.orderinfodetail.adapter.BannerAdapter;
import com.homegoods.orderinfodetail.databinding.InfoOrderDetailActvityBinding;
import com.homegoods.orderinfodetail.model.BannerGoodsBean;
import com.homegoods.orderinfodetail.model.DisCountModel;
import com.homegoods.orderinfodetail.model.GoodsDetailTypeBean;
import com.homegoods.orderinfodetail.model.GoodsParamModel;
import com.homegoods.orderinfodetail.model.OrderInfoDetailModel;
import com.homegoods.orderinfodetail.model.SKUValueModel;
import com.homegoods.orderinfodetail.presenter.OrderInfoDetailPresenter;
import com.homegoods.orderinfodetail.ui.fragment.AddShopCarDialog;
import com.homegoods.orderinfodetail.ui.fragment.ChoicePatternDialog;
import com.homegoods.orderinfodetail.ui.fragment.GoodParamDialog;
import com.homegoods.orderinfodetail.ui.fragment.ServiceDialogFragment;
import com.homegoods.orderinfodetail.ui.view.IDetailView;
import com.homegoods.resource.util.Utils;
import com.kedll.library.adapter.MultiTypeAdapter;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.util.MyUtils;
import com.kedll.library.util.StringUtil;
import com.share.sharelibrary.share.ShareData;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.jzvd.Jzvd;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * @author QiQi
 * @description 商品详情页
 */
@Route(path = ARouterPath.PATH_GOODS_DETAIL)
public class OrderInfoDetailActivity extends MyBaseFragmentActivity<InfoOrderDetailActvityBinding, OrderInfoDetailPresenter> implements AppBarLayout.OnOffsetChangedListener, NestedScrollView.OnScrollChangeListener, IDetailView {
    /**
     * 商品ID
     */
    @Autowired
    public String sid;
    @Autowired(name = ARouterPath.PATH_USER_SERVICE)
    public UserService userService;
    private ArgbEvaluator argbEvaluator;
    private OrderInfoDetailModel mInfoModel;
    private ChoicePatternDialog choicePatternDialog;
    private AddShopCarDialog addShopCarDialog;  //add shibo.zheng
    private MultiTypeAdapter adapter;

    @Override
    protected int getLayout() {
        return R.layout.info_order_detail_actvity;
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initEvent() {
        mBinding.appBarLayout.addOnOffsetChangedListener(this);
        mBinding.detailsScrollView.setOnScrollChangeListener(this);

        //商品收藏
        onClicked(mBinding.infoCollect, o -> {
            mPresenter.addCollect(sid);
        });


        //退出
        onClicked(mBinding.detailsBackImage, o -> finish());


        //加入到购物车
        onClicked(mBinding.detailsAddCart, o -> mPresenter.getSpecifications(sid)
                .map(s -> JSON.parseArray(s, GoodsDetailTypeBean.class))
                .compose(OrderInfoDetailActivity.this.bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(goodsDetailTypeBeans -> {
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) goodsDetailTypeBeans);
                    bundle.putSerializable("goods", mInfoModel);
                    addShopCarDialog.showDialog(OrderInfoDetailActivity.this.getSupportFragmentManager(), bundle, "AddShopCarDialog");
                }));
        //显示类型选项
        onClicked(mBinding.detailsSelectColor, new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {

                mPresenter.getSpecifications(sid)
                        .map(new Function<String, List<OrderInfoDetailModel.SkuListBean>>() {
                            @Override
                            public List<OrderInfoDetailModel.SkuListBean> apply(String s) throws Exception {
                                return JSON.parseArray(s, OrderInfoDetailModel.SkuListBean.class);
                            }
                        })
                        .compose(OrderInfoDetailActivity.this.bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(goodsDetailTypeBeans -> {
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) goodsDetailTypeBeans);
                    bundle.putSerializable("goods", mInfoModel);
                    choicePatternDialog.showDialog(OrderInfoDetailActivity.this.getSupportFragmentManager(), bundle, "ChoicePatternDialog");
                });
            }
        });
        //显示参数
        //del shibo.zheng 19/06/28 start
        /*onClicked(mBinding.detailsSelectParam, o -> {
            mPresenter.getParameter(sid)
                    .map(s -> JSON.parseArray(s, GoodsParamModel.class))
                    .compose(bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(paramModels -> {
                        Bundle bundle = new Bundle();
                        bundle.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) paramModels);
                        new GoodParamDialog().showDialog(getSupportFragmentManager(), bundle, "goodsParamsDialog");
                    });
        });*/
        //del shibo.zheng 19/06/28 end

        //显示宅品服务
        //del shibo.zheng 19/06/28
//        onClicked(mBinding.detailsService, o -> new ServiceDialogFragment().showDialog(getSupportFragmentManager(), "serviceDialog"));

        //跳转到商品评价列表
//        onClicked(mBinding.llComment, o -> mPresenter.showCommentList());

//        onClicked(mBinding.detailsShareImage, o -> new ShareData.Builder()
//                .setShareType(ShareData.SHARE_WEB)
//                .setUrl("http://www.baidu.com")
//                .builder()
//                .startShare());

        //店铺详情（暂时没有店铺的概念）
//        onClicked(mBinding.btnShopDetail, o -> mPresenter.showShop(mInfoModel.getBusinessman().getSid()));

        //立即购买
        onClicked(mBinding.detailsBuy, o -> mPresenter.buyImmediately());

        //购物车
        //del shibo.zheng 19/06/28
//        onClicked(mBinding.tvShoppingCart, o -> mPresenter.showShoppingCar());

        //店铺客服
        onClicked(mBinding.tvShoppingService, new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
//                mPresenter.showService();
                call("10086");
            }
        });

        //add shibo.zheng
        //商品详情界面点击图片后预览
        mBinding.flBanner.setOnItemClickListener(position -> mPresenter.bannerItemClick(position));

        //加载界面数据

        mPresenter.loadData(sid);
        choicePatternDialog = new ChoicePatternDialog();
        choicePatternDialog.setCallBack(content -> {
            mBinding.detailsSelectColor.setAcTitle(content);
        });

        //add shibo.zheng start 解决添加购物车时未选择参数，点击关闭按钮callback为null报错
        addShopCarDialog = new AddShopCarDialog();
        addShopCarDialog.setCallBack(content -> mBinding.detailsSelectColor.setAcTitle(content));
        //add shibo.zheng end

        //add shibo.zheng 19/06/27 start
        adapter = new FlexBoxAdapter(getApplicationContext(), 4);
        List<DisCountModel> disCountData = getDisCountData();
        if (disCountData != null && disCountData.size() > 0) {
            for (DisCountModel model : disCountData) {
                adapter.addItem(model.createItem(adapter));
            }
        }

        initListView(mBinding.discontList, adapter);

//        mBinding.rbStar.setStar(4);
    }

    /**
     * 初始化优惠信息列表控件
     * @param list
     * @param adapter
     */
    private void initListView(RecyclerView list, MultiTypeAdapter adapter) {
        list.setLayoutManager(MyUtils.getFlexBoxLayoutManager(this));
        list.setHasFixedSize(false);
        list.setNestedScrollingEnabled(false);
        list.setAdapter(adapter);
    }

    /**
     * 测试数据
     * @return
     */
    private List<DisCountModel> getDisCountData() {
        List<DisCountModel> disCountModels = new ArrayList<>();
//        if (mInfoModel != null) {
            DisCountModel model1 = new DisCountModel("包邮");
            DisCountModel model2 = new DisCountModel("100积分兑换一元");
            disCountModels.add(model1);
            disCountModels.add(model2);
//        }
        return disCountModels;
    }
    //add shibo.zheng 19/06/27 end

    @Override
    protected void onStart() {
        super.onStart();
        MyUtils.setSystemUi(getWindow(), false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isFinishing()) {
            MyUtils.setSystemUi(getWindow(), true);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    @Override
    public void showLoad(String msg) {

    }

    @Override
    public void hideLoad() {

    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        ARouter.getInstance().inject(this);
        argbEvaluator = new ArgbEvaluator();
        initBanner();
    }

    private void initBanner() {
        //初始化轮播图
        mBinding.flBanner.getViewPager().setClipToPadding(false);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mBinding.flBanner.getViewPager().getLayoutParams();
        params.leftMargin = 0;
        params.rightMargin = 0;
    }

    @Override
    protected void initToolBar(Bundle savedInstanceState) {
        super.initToolBar(savedInstanceState);
    }

    @Override
    protected OrderInfoDetailPresenter getPresenter() {
        return new OrderInfoDetailPresenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBinding.appBarLayout.removeOnOffsetChangedListener(this);
        Jzvd.releaseAllVideos();
    }

    @Override
    public void setBanner(List<BannerGoodsBean> goodsBeans) {
        mBinding.tvIndicator.setText(String.format("%s/%s", 1, goodsBeans.size()));
        mBinding.flBanner.setPages((CBViewHolderCreator<BannerAdapter>) BannerAdapter::new, goodsBeans)
                .setOnPageChangeListener(new MySimpleOnPageChangeListener(this, goodsBeans.size()));

    }

    @Override
    public void setGoods(OrderInfoDetailModel model) {
        Log.d(TAG, "setGoods: model == " + model);
        mInfoModel = model;
        //设置商品名称
        mBinding.tvTitle.setText(model.getProductName());
        //add shibo.zheng 19/06/27 start
        //此处需要添加小数点后面的字体大小为11
//        String nowPrice = "￥" + model.getMinPrice();
//        SpannableString spannable = new SpannableString(nowPrice);
//        AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(24, true); //设置字体大小为24dip， true为dip， false为px
//        String subPrice = nowPrice.substring(0, nowPrice.indexOf(".")); //截取"."前面的字符
//        spannable.setSpan(sizeSpan, 1, subPrice.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);    //第一位至截取后的长度字符串设置特殊字体大小
////        mBinding.tvPrice.setText(String.format("￥%s", model.getNowPrice()));
//        mBinding.tvPrice.setText(spannable);    //此处只能设置一个spanable，不能使用拼接或者string.format等，否则设置大小不生效
        mBinding.tvPrice.setText(Utils.getPrice(model.getMinPrice()));
        //add shibo.zheng 19/06/27 end
        //del shibo.zheng 19/06/27 start
//        mBinding.tvActivityPrice.setText(String.format("￥%s", MyUtils.getActivityPrice(model.getNowPrice(), model.getPayCake())));
//        mBinding.tvDayang.setText(String.format("%s积分", MyUtils.getActivityTegral(model.getNowPrice(), model.getPayCake())));
        //del shibo.zheng 19/06/27 end
        //设置店铺名称
//        mBinding.tvShopName.setText("中企宅品");
//        mBinding.tvShopIntro.setText(model.getBusinessman().getIntro());  //del shibo.zheng 19/06/28
//        Bundle bundle = new Bundle();
//        bundle.putString("url", model.getProductsurl());
//        GoodsInfoWebFragment fragment = new GoodsInfoWebFragment();
//        fragment.setArguments(bundle);
//        getSupportFragmentManager().beginTransaction().replace(R.id.goods_detail, fragment).commit();

        //付款人数
        mBinding.payNum.setText(model.getSaleNum());

        //发货地址
        mBinding.areaText.setText(model.getAddress());

        //保障权益（如七天无理由退货等）
        if (model.getEnsure() != null) {
            mBinding.protectionText.setText(model.getEnsure());
        }
        /*String dataStr = "<html>\n" +
                "<body>\n" +
                "<style>img{ width:100% !important;}</style>\n" +
                "        <img src=https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/dd9d1d686cdc814db9653b254e00402e_259_194.jpg>\n" +
                "        <p style=text-align:right;>品类定位的思考</p><h3><strong><span style=color:#00D5FF;>品类定</span></strong>\n" +
                "        <h3><a href='JavaScript:android.returnAndroid(要返回给APP的数据)'>点击我跳回APP</a>\n" +
                "</body>\n" +
                "</html>";*/
        initWebViewAndSetData(mBinding.wvGoodsDetail, model.getProductDetailed());

    }

    private void initWebViewAndSetData(WebView webView, String dataStr) {
        //硬件加速
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.getSettings().setBlockNetworkImage(false);
        webView.setDrawingCacheEnabled(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        //支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        //设置可以支持缩放
        webView.getSettings().setSupportZoom(true);
        //设置出现缩放工具
        webView.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        webView.getSettings().setUseWideViewPort(true);
        //自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);

        //设置WebView的样式,编码格式.
        webView.loadDataWithBaseURL("", dataStr, "text/html", "UTF-8", "about:blank");
    }

    /**
     * 调用拨号界面
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    //sku属性选择
    @Override
    public void setSKUList(OrderInfoDetailModel model) {
        Log.d(TAG, "setSKUList: model attrs = " + model.getCategories().get(0).getValues().get(0));
        onClicked(mBinding.detailsSelectColor, new Consumer<Object>() {
            @SuppressLint("CheckResult")
            @Override
            public void accept(Object o) throws Exception {
                Log.d(TAG, "accept:  o == " + o);
//                List<OrderInfoDetailModel.SkuListBean> skuList = model.getSkuList();
                List<OrderInfoDetailModel.CategoriesBean> categories = model.getCategories();
//                OrderInfoDetailModel.CategoriesBean categoriesBean = new OrderInfoDetailModel.CategoriesBean();
//                List<SKUValueModel> skuValueModels = new ArrayList<>();
//                SKUValueModel skuValueModel = new SKUValueModel();
//                skuValueModel.setName(model.getCategories().get(0).getValues().get(0));
//                skuValueModels.add(skuValueModel);
//                categoriesBean.setSkuValues(skuValueModels);
                Bundle bundle = new Bundle();
                Log.d(TAG, "accept: categores == " + JSON.toJSONString(categories));
                bundle.putParcelableArrayList("data", /*(ArrayList<? extends Parcelable>) model.getCategories()*/(ArrayList<? extends Parcelable>) categories);
                bundle.putSerializable("goods", model);
                choicePatternDialog.showDialog(OrderInfoDetailActivity.this.getSupportFragmentManager(), bundle, "ChoicePatternDialog");
//                        });

            }
        });
    }


    /**
     * AppBarLayout 滑动监听
     *
     * @param appBarLayout
     * @param verticalOffset
     */
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        float mMoveDistance = (Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange());
        int alpha = (int) ((1 - mMoveDistance) * 255);
        //圆形背景
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.draw_gray_circle_shape);
        //返回图标
        Drawable backDrawable = ContextCompat.getDrawable(this, R.drawable.ic_arrow_back_white);
        //分享图标
        Drawable shareDrawable = ContextCompat.getDrawable(this, R.mipmap.info_icon_share);
        //主页图标
        Drawable homeDrawable = ContextCompat.getDrawable(this, R.mipmap.icon_home);
        //计算图标从白到黑过程中的色值
        int currentColor = (int) argbEvaluator.evaluate(mMoveDistance, Color.WHITE, Color.BLACK);

        if (drawable != null && backDrawable != null && shareDrawable != null && homeDrawable != null) {
            //设置圆形背景的透明度
            drawable.setAlpha(alpha);
            mBinding.detailsBackImage.setBackground(drawable);
            mBinding.detailsShareImage.setBackground(drawable);
            mBinding.detailsHomeImage.setBackground(drawable);


            //设置变色后的各个图标
            DrawableCompat.setTint(backDrawable, currentColor);
            mBinding.detailsBackImage.setImageDrawable(backDrawable);

            DrawableCompat.setTint(shareDrawable, currentColor);
            mBinding.detailsShareImage.setImageDrawable(shareDrawable);

            DrawableCompat.setTint(homeDrawable, currentColor);
            mBinding.detailsHomeImage.setImageDrawable(homeDrawable);
        }

        if (mBinding.flBanner.getCurrentItem() == 0) {
            if (mMoveDistance == 1) {
                Jzvd.goOnPlayOnPause();
            } else {
                Jzvd.goOnPlayOnResume();
            }
        }

    }

    @Override
    public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX,
                               int oldScrollY) {
        int mGradualChange = mBinding.llHead.getMeasuredHeight();
        int startOffset = 0;
        if (scrollY <= startOffset) {
            mBinding.detailsToolbarTitle.setTranslationY(mGradualChange);
        } else if (scrollY < mGradualChange) {
            mBinding.detailsToolbarTitle.setTranslationY(mGradualChange - scrollY);
        } else {
            mBinding.detailsToolbarTitle.setTranslationY(0);
        }
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    private static class MySimpleOnPageChangeListener extends SimpleOnPageChangeListener {
        private final int size;
        private final ArgbEvaluator argbEvaluator;
        private final int[][] colors;
        int mPrevStartColor;
        int mPrevEndColor;
        int mNextStartColor;
        int mNextEndColor;
        int mPrevStartTextColor;
        int mPrevEndTextColor;
        int mNextStartTextColor;
        int mNextEndTextColor;
        OrderInfoDetailActivity detailActivity;
        private Drawable playDraw;

        MySimpleOnPageChangeListener(OrderInfoDetailActivity context, int size) {
            this.detailActivity = context;
            this.size = size;
            colors = new int[][]{
                    {Color.TRANSPARENT, ContextCompat.getColor(context, R.color.color_b2ffffff)},
                    {Color.WHITE, ContextCompat.getColor(context, R.color.color_333333)}
            };
            mPrevStartColor = colors[0][0];
            mPrevEndColor = colors[0][1];

            mNextStartColor = colors[0][1];
            mNextEndColor = colors[0][0];

            mPrevStartTextColor = colors[1][0];
            mPrevEndTextColor = colors[1][1];

            mNextStartTextColor = colors[1][1];
            mNextEndTextColor = colors[1][0];

            argbEvaluator = new ArgbEvaluator();

            playDraw = context.mBinding.ivPlay.getDrawable();
        }


        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            //色块跟随轮播移动
            if (position % size == 0 && positionOffset > 0) {
                detailActivity.mBinding.vCourse.setTranslationX(MyUtils.dp2px(64) * positionOffset);

                int mPrevColor = (int) argbEvaluator.evaluate(positionOffset, mPrevStartColor, mPrevEndColor);
                int mNextColor = (int) argbEvaluator.evaluate(positionOffset, mNextStartColor, mNextEndColor);
                detailActivity.mBinding.llVideo.setBackgroundColor(mPrevColor);
                detailActivity.mBinding.tvImg.setBackgroundColor(mNextColor);

                int mPrevTextColor = (int) argbEvaluator.evaluate(positionOffset, mPrevStartTextColor, mPrevEndTextColor);
                int mNexTextColor = (int) argbEvaluator.evaluate(positionOffset, mNextStartTextColor, mNextEndTextColor);
                detailActivity.mBinding.tvVideo.setTextColor(mPrevTextColor);
                detailActivity.mBinding.tvImg.setTextColor(mNexTextColor);

                DrawableCompat.setTint(playDraw, mPrevTextColor);
                detailActivity.mBinding.ivPlay.setImageDrawable(playDraw);

            } else if (position % size == 1 && positionOffset < 0) {
                detailActivity.mBinding.vCourse.setTranslationX(MyUtils.dp2px(64) * (1 + positionOffset));

                int mPrevColor = (int) argbEvaluator.evaluate((1 + positionOffset), mPrevStartColor, mPrevEndColor);
                int mNextColor = (int) argbEvaluator.evaluate((1 + positionOffset), mNextStartColor, mNextEndColor);
                detailActivity.mBinding.llVideo.setBackgroundColor(mNextColor);
                detailActivity.mBinding.tvImg.setBackgroundColor(mPrevColor);

                int mPrevTextColor = (int) argbEvaluator.evaluate((1 + positionOffset), mPrevStartTextColor, mPrevEndTextColor);
                int mNexTextColor = (int) argbEvaluator.evaluate((1 + positionOffset), mNextStartTextColor, mNextEndTextColor);
                detailActivity.mBinding.tvVideo.setTextColor(mNexTextColor);
                detailActivity.mBinding.tvImg.setTextColor(mPrevTextColor);

                DrawableCompat.setTint(playDraw, mNexTextColor);
                detailActivity.mBinding.ivPlay.setImageDrawable(playDraw);
            }

            if (positionOffset == 0) {
                if (position % size == 0) {
                    detailActivity.mBinding.llVideo.setBackgroundColor(mPrevStartColor);
                    detailActivity.mBinding.tvImg.setBackgroundColor(mPrevEndColor);

                    detailActivity.mBinding.tvVideo.setTextColor(mNextEndTextColor);
                    detailActivity.mBinding.tvImg.setTextColor(mPrevEndTextColor);

                    DrawableCompat.setTint(playDraw, mNextEndTextColor);
                    detailActivity.mBinding.ivPlay.setImageDrawable(playDraw);

                    detailActivity.mBinding.vCourse.setTranslationX(0);
                } else if (position % size == 1) {
                    detailActivity.mBinding.llVideo.setBackgroundColor(mPrevEndColor);
                    detailActivity.mBinding.tvImg.setBackgroundColor(mPrevStartColor);

                    detailActivity.mBinding.tvVideo.setTextColor(mPrevEndTextColor);
                    detailActivity.mBinding.tvImg.setTextColor(mNextEndTextColor);

                    DrawableCompat.setTint(playDraw, mPrevEndTextColor);
                    detailActivity.mBinding.ivPlay.setImageDrawable(playDraw);

                    detailActivity.mBinding.vCourse.setTranslationX(MyUtils.dp2px(64));
                }
            }

        }

        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            detailActivity.mBinding.tvIndicator.setText(String.format("%s/%s", position + 1, size));
            if (position > 0) {
                Jzvd.goOnPlayOnPause();
            } else {
                Jzvd.goOnPlayOnResume();
            }
        }
    }

    private static class FlexBoxAdapter extends MultiTypeAdapter {

        private int itemWidth;

        public FlexBoxAdapter(Context context, int itemCount) {
            itemWidth = context.getResources().getDisplayMetrics().widthPixels / itemCount;
        }

        @Override
        public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
            super.onBindViewHolder(holder, position);
            View view = holder.getBinding().getRoot().findViewById(R.id.tv_discount);
            ViewGroup.LayoutParams lp = view.getLayoutParams();
            if (lp instanceof FlexboxLayoutManager.LayoutParams) {
                FlexboxLayoutManager.LayoutParams flexboxLp = (FlexboxLayoutManager.LayoutParams) lp;
                flexboxLp.setMinWidth(itemWidth);
                flexboxLp.setFlexGrow(1.0f);
            }

        }
    }
}
